// ignore_for_file: unnecessary_overrides, prefer_typing_uninitialized_variables, non_constant_identifier_names, unused_local_variable

import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:get/get.dart';
import 'package:verse_systems/commom/global/global.dart';
import 'package:verse_systems/commom/models/bank_model.dart';
import 'package:verse_systems/commom/models/contact_model.dart';
import 'package:verse_systems/commom/routers/navigator_utils.dart';
import 'package:verse_systems/commom/routers/routes_pages_name.dart';
import 'package:verse_systems/pages/authentication/authentication_state.dart';
import 'package:verse_systems/pages/home/home_control.dart';
import 'package:verse_systems/pages/picker/choose_data_picker.dart';
import 'package:verse_systems/pages/picker/choose_picker_view.dart';
import 'package:verse_systems/pages/picker/city_picker_view.dart';
import 'package:verse_systems/pages/picker/city_result.dart';
import 'package:verse_systems/utils/account_util.dart';
import 'package:verse_systems/net/http_dio.dart';
import 'package:verse_systems/utils/loading.dart';
import 'package:verse_systems/utils/utils.dart';
import 'package:verse_systems/widgets/alert.dart';

class AuthenticationControl extends GetxController {
  static BuildContext context =
      Global.navigatorKey.currentState!.overlay!.context;

  final AuthenticationState state = AuthenticationState();

  final TextEditingController name = TextEditingController();
  final TextEditingController idNumber = TextEditingController();
  final TextEditingController gender = TextEditingController();

  // 居住城市详细地址
  final TextEditingController user_city_of_residence_edit =
      TextEditingController();
  //  工作城市详细地址
  TextEditingController user_city_of_work_edit = TextEditingController();

  //银行卡
  final TextEditingController bankcard_code = TextEditingController();
  //银行卡号
  final TextEditingController bankcard_number = TextEditingController();
  //持卡人姓名
  final TextEditingController real_name = TextEditingController();
  //支付宝账号
  final TextEditingController alipay_account = TextEditingController();

  MethodChannel eventChannel = const MethodChannel('open_native_camera');

  final home_control = Get.find<HomeControl>();

openAlbum(){
   eventChannel.invokeMethod("open_album").then((value) async {
      if (Platform.isAndroid) {
        if (value == true) {
          //获取相册授权
          String base64 = await Utils.openAlbum();
          uploadImage(imgType: "alipay-code", base64: base64);
        }
      } else {
        String base64 = value["image"];
         uploadImage(imgType: "alipay-code", base64: base64);
      }
    });
}


//上传银行卡信息
  handleUploadBankCardInfo() async {
    if (bankcard_code.text.trim() == '') {
      return Loading.showError("please_select_bank".tr);
    }
    if (bankcard_number.text.trim() == '') {
      return Loading.showError("please_enter_bank_number".tr);
    }
    if (real_name.text.trim() == '') {
      return Loading.showError("please_enter_cardholder".tr);
    }
     
    if (state.upload == true) {
       if (alipay_account.text.trim() == '') {
        return Loading.showError("please_enter_alipay_account".tr);
       }
    }  
    if (state.upload == true &&  state.required == true) {
       if (state.alipay_code_path == '') {
        return Loading.showError("please_upload_alipay_code".tr);
       }
    } 

    Alert.showChoiceInfoSheet(
        title: "please_confirm".tr,
        name: bankcard_code.text,
        real_name: "bank".tr,
        number: bankcard_number.text,
        real_name_number: "bank_number".tr,
        gender: real_name.text,
        real_name_gender: "cardholder_name".tr,
        alipay_account: "alipay_account".tr,
        alipay_code: alipay_account.text,
        onPressed: () async {
          final String token = await AccountUtil.getUserToken();
          final borrowId = Get.arguments["borrow_id"];
          final country = Get.arguments["country"];
          Map<String, dynamic> map = HashMap();
          map['token'] = token;
          map['borrow_id'] = borrowId;
          map['country'] = country;
          map['bankcard_code'] = state.bankcard_code;
          map['bankcard_number'] = bankcard_number.text;
          map['real_name'] = real_name.text;
          if (state.upload == true) {
              map['alipay_account'] = alipay_account.text;
          } 
          //二维码上传参数
          if (state.upload == true&& state.required == true) {
              map['alipay_code'] = state.alipay_code_path;
          } 
          debugPrint("上传银行卡信息---$map");
          Request.postCallback(
            HttpUrls.uploadBankCardInfo,
            data: map,
            success: (res) async {
              ResultData result = ResultData.fromJson(res.data);
              if (result.status == 0) {
                debugPrint("getBankCardInfoList--$result");
                home_control.nextCertification(borrowId: borrowId);
              } else {
                Loading.showError(result.msg);
              }
            },
          );
        });
  }

  getBankCardInfoList() async {
    final String token = await AccountUtil.getUserToken();
    final borrowId = Get.arguments["borrow_id"];
    final country = Get.arguments["country"];
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    map['country'] = country;

    Request.postCallback(
      HttpUrls.getBankCardInfoList,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          state.bank_notice_info = result.data["notice"];
          state.bankcard = result.data["enumeration"]["bankcard"];
          final record = result.data["record"];
          final List bankcard_results = state.bankcard
              .where((model) => model["key"] == (record["bankcard_code"]))
              .toList();
          if (bankcard_results.isNotEmpty) {
            bankcard_code.text = bankcard_results.first["value"].toString();
            state.bankcard_code = record["bankcard_code"].toString();
          }
          if (record["bankcard_number"] != null) {
            bankcard_number.text = record["bankcard_number"];
          }
          if (record["real_name"] != null) {
            real_name.text = record["real_name"];
          }
          final alipay  = result.data["record"]["alipay"];
          if (alipay["alipay_account"] != null) {
             alipay_account.text = alipay["alipay_account"];
          }
          
          //支付宝是否展示
          if (alipay["upload"] != null) {
             state.upload =  alipay["upload"];
          }

          //支付宝是否必传
          if (alipay["required"] != null) {
             state.required =  alipay["required"];
          }

          if (alipay["explain"] != null) {
             state.alipay_info_explain =  alipay["explain"];
          }
          
          if (alipay["alipay_code"] != null) {
             final alipay_code = alipay["alipay_code"];
             if (alipay_code["path"]!= null) {
                 state.alipay_code_path = alipay_code["path"];
             }
             if (alipay_code["url"]!= null) {
                 state.alipay_code_url = alipay_code["url"];
             }
          }


             
          //alipay_code
          update();
        }
      },
    );
  }

  onPressedBank() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: false,
      builder: (ctx) {
        return ChoosePickerView(
          onResult: (result) {
            debugPrint("银行卡信息认证方式--$result");
            bankcard_code.text = result["value"];
            state.bankcard_code = result["key"].toString();
          },
          params: state.bankcard,
        );
      },
    );
  }




  handleBankNext() async {
    if (state.country == '') {
      return Loading.showError("please_select_card_infor_method".tr);
    }

    final borrowId = Get.arguments["borrow_id"];
    Get.toNamed(RoutesPage.AuthenticationBankInfo,
        arguments: {"borrow_id": borrowId, "country": state.country});
  }

  handleNext() async {
    if (state.positive.trim() == '') {
      return Loading.showError("please_upload_front_photo".tr);
    }

    if (state.reverse.trim() == '') {
      return Loading.showError("please_upload_back_photo".tr);
    }
    if (state.openOcr) {
      if (state.face.trim() == '') {
        return Loading.showError("please_upload_face_photo".tr);
      }
    }

    if (name.text.trim() == '') {
      return Loading.showError("please_enter_name".tr);
    }

    if (idNumber.text.trim() == '') {
      return Loading.showError("please_enter_id_number".tr);
    }
    if (gender.text.trim() == '') {
      return Loading.showError("please_select_gender".tr);
    }
    if (state.agreementIsChecked == false) {
      return Loading.showError("please_check_info_authorization".tr);
    }

    Alert.showChoiceInfoSheet(
        title: "please_confirm".tr,
        name: name.text,
        number: idNumber.text,
        gender: gender.text,
        onPressed: uploadInfo);
  }




  uploadBasicInfo() async {
    if (state.user_loan_purpose == '') {
      return Loading.showError("please_select_purpose".tr);
    }
    if (state.user_education == '') {
      return Loading.showError("please_select_degree".tr);
    }
    if (state.user_marital_status == '') {
      return Loading.showError("please_select_marita".tr);
    }
    if (state.user_date_of_birth == '') {
      return Loading.showError("please_select_birthday".tr);
    }
    if (state.user_city_of_residence == '') {
      return Loading.showError("please_select_reside_address".tr);
    }

    if (user_city_of_residence_edit.text.trim() == '') {
      return Loading.showError("please_select_reside_full_address".tr);
    }
    if (state.user_occupation == '') {
      return Loading.showError("please_select_occupation".tr);
    }
    if (state.user_sesame_score == '') {
      return Loading.showError("please_select_sesame_level".tr);
    }
    if (state.user_city_of_work == '') {
      return Loading.showError("please_select_city_work".tr);
    }

    if (user_city_of_work_edit.text.trim() == '') {
      return Loading.showError("please_select_city_work_full_address".tr);
    }

    if (state.user_emergency_relation_one == '') {
      return Loading.showError("please_select_contact_one_relation".tr);
    }
    if (state.user_emergency_phone_one == '') {
      return Loading.showError("please_select_contact_one".tr);
    }
    if (state.user_emergency_relation_two == '') {
      return Loading.showError("please_select_contact_two_relation".tr);
    }
    if (state.user_emergency_phone_two == '') {
      return Loading.showError("please_select_contact_two".tr);
    }


    final String token = await AccountUtil.getUserToken();
    final borrowId = Get.arguments["borrow_id"];
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    map['date_of_birth'] = state.user_date_of_birth;
    map['marital_status'] = state.user_marital_status;
    map['education'] = state.user_education;
    map['occupation'] = state.user_occupation;

    final user_city_of_residence =
        "${state.user_city_of_residence},${user_city_of_residence_edit.text}";
    map['city_of_residence'] = user_city_of_residence.split(',');
    final user_city_of_work =
        "${state.user_city_of_work},${user_city_of_work_edit.text}";
    map['city_of_work'] = user_city_of_work.split(',');
    map['loan_purpose'] = state.user_loan_purpose;
    map['sesame_score'] = state.user_sesame_score;
    map['contacts'] = [
      {
        "emergency_name": state.user_emergency_name_one, //联系人名称
        "emergency_phone": state.user_emergency_phone_one, //联系人号码
        "emergency_relation": state.user_emergency_relation_one //联系人关系
      },
      {
        "emergency_name": state.user_emergency_name_two, //联系人名称
        "emergency_phone": state.user_emergency_phone_two, //联系人号码
        "emergency_relation": state.user_emergency_relation_two //联系人关系
      },
    ];

    debugPrint("uploadBasicInfo ---->$map");
    Loading.show("上传中...");
    Request.postCallback(
      HttpUrls.uploadInfoDetail,
      data: map,
      success: (res) async {
        Loading.dismiss();
        ResultData result = ResultData.fromJson(res.data);

        if (result.status == 0) {
          debugPrint("上传基本信息成功--$result");
          home_control.nextCertification(borrowId: borrowId);
        }
      },
      error: (err) {
        Loading.dismiss();
      },
    );
  }

  Future<DateTime?> selectDate(BuildContext context) async {
    DateTime? picked = await showDatePicker(
        context: context,
        initialDate: DateTime.now(),
        firstDate: DateTime(1900),
        lastDate: DateTime(2100));
    return picked;
  }

  handleGenderInfo() {
    showModalBottomSheet(
      context: context,
      isScrollControlled: false,
      builder: (ctx) {
        return ChoosePickerView(
          onResult: (result) {
            gender.text = result["value"];
          },
          params: const [
            {"value": "男", "key": 1},
            {"value": "女", "key": 2},
          ],
        );
      },
    );
  }

  getContactInfo() async {
    getInfoDetails();
    final contact = await rootBundle.loadString('assets/contact.json');
    List data = json.decode(contact) as List;
    state.contact = data.map((json) => ContactModel.fromJson(json)).toList();
    update();
  }

  handleProtocol() {
    NavigatorUtils.handleProductWeb(url: state.idcardAuthorization);
  }

  jumpToAuthenPoint() async {
    Get.toNamed(RoutesPage.AuthenticationPoint);
  }

  handlePersonalInfo({required int? index, required ContactModel model}) {
    debugPrint("index----$index");

    switch (index) {
      case 0:
        {
          //贷款用途
          showModalBottomSheet(
            context: context,
            isScrollControlled: false,
            builder: (ctx) {
              return ChoosePickerView(
                onResult: (result) {
                  model.value = result["value"];
                  state.user_loan_purpose = result["key"].toString();

                  update();
                },
                params: state.loan_purpose,
              );
            },
          );
        }

        break;
      case 1:
        {
          //学历
          showModalBottomSheet(
            context: context,
            isScrollControlled: false,
            builder: (ctx) {
              return ChoosePickerView(
                onResult: (result) {
                  model.value = result["value"];
                  state.user_education = result["key"].toString();
                  update();
                },
                params: state.education,
              );
            },
          );
        }

        break;
      case 2:
        {
          //婚姻状况
          showModalBottomSheet(
            context: context,
            isScrollControlled: false,
            builder: (ctx) {
              return ChoosePickerView(
                onResult: (result) {
                  model.value = result["value"];
                  state.user_marital_status = result["key"].toString();
                  update();
                },
                params: state.marital_status,
              );
            },
          );
        }

        break;
      case 3: //生日
        {
          showModalBottomSheet(
            context: context,
            isScrollControlled: false,
            builder: (ctx) {
              return ChooseDataPicker(
                onResult: (String result) {
                  debugPrint("生日--$result");
                  model.value = result;
                  state.user_date_of_birth = result;
                  update();
                },
              );
            },
          );
        }
        break;
      case 4:
        {
          //居住地址

          showModalBottomSheet(
            context: context,
            isScrollControlled: true,
            builder: (ctx) {
              return CityPickerView(
                onResult: (CityResult res) {
                  debugPrint(res.toJson().toString());
                  model.value = "${res.province},${res.city},${res.area}";
                  state.user_city_of_residence =
                      "${res.province},${res.city},${res.area}";
                  update();
                },
              );
            },
          );
        }
        break;
      case 5:
        {
          debugPrint("居住详细地址");
        }
        break;
      case 7:
        {
          //职业
          showModalBottomSheet(
            context: context,
            isScrollControlled: false,
            builder: (ctx) {
              return ChoosePickerView(
                onResult: (result) {
                  model.value = result["value"];
                  state.user_occupation = result["key"].toString();
                  update();
                },
                params: state.occupation,
              );
            },
          );
        }
        break;
      case 8:
        {
          //芝麻分
          showModalBottomSheet(
            context: context,
            isScrollControlled: false,
            builder: (ctx) {
              return ChoosePickerView(
                onResult: (result) {
                  model.value = result["value"];
                  state.user_sesame_score = result["key"].toString();
                  update();
                },
                params: state.sesame_score,
              );
            },
          );
        }
        break;
      case 9:
        {
          //工作地址

          showModalBottomSheet(
            context: context,
            isScrollControlled: true,
            builder: (ctx) {
              return CityPickerView(
                onResult: (CityResult res) {
                  debugPrint(res.toJson().toString());
                  model.value = "${res.province},${res.city},${res.area}";
                  state.user_city_of_work =
                      "${res.province},${res.city},${res.area}";
                  update();
                },
              );
            },
          );
        }
        break;

      case 10:
        {
          debugPrint("公司详细地址");
        }
        break;

      //常用联系人关系1关系
      case 12:
        {
          showModalBottomSheet(
            context: context,
            isScrollControlled: false,
            builder: (ctx) {
              return ChoosePickerView(
                onResult: (result) {
                  model.value = result["value"];
                  state.user_emergency_relation_one = result["key"].toString();
                  update();
                },
                params: state.emergency_relation,
              );
            },
          );
        }
        break;
      case 13:
        {
          eventChannel.invokeMethod("open_contact").then((value) {
            debugPrint("联系人1--${value.toString()}");
            String phone = value["phone"];
            model.value = value["phone"];
            state.user_emergency_name_one = value["name"]; //联系人1
            state.user_emergency_phone_one = value["phone"]; //联系人1电话
            debugPrint(phone);
            update();
          });
        }
        break;
      case 15: //常用联系人关系
        {
          showModalBottomSheet(
            context: context,
            isScrollControlled: false,
            builder: (ctx) {
              return ChoosePickerView(
                onResult: (result) {
                  model.value = result["value"];
                  state.user_emergency_relation_two = result["key"].toString();
                  update();
                },
                params: state.emergency_relation,
              );
            },
          );
        }
        break;
      case 16:
        {
          eventChannel.invokeMethod("open_contact").then((value) {
            debugPrint("联系人2--${value.toString()}");
            model.value = value["phone"];
            state.user_emergency_name_two = value["name"]; //联系人2
            state.user_emergency_phone_two = value["phone"]; //联系人2电话
            update();
          });
        }
        break;

      default:
    }
  }

  void jumpOpenCamera({String? image}) async {
    if (Platform.isAndroid) {
         //获取相机授权
      eventChannel.invokeMethod("open_camera").then((value) async {
        if (value == true) {
            String base64 = await Utils.openCamera();
            uploadImage(imgType: image,base64: base64);
        }
      });
    } else {
      if (image == "ocr-image") {
        eventChannel.invokeMethod("open_face").then((value) {
          String base64 = value["pic"];
          uploadImage(imgType: image, base64: base64);
        });
      } else {
        eventChannel.invokeMethod("open_camera").then((value) {
          String base64 = value["image"];
          uploadImage(imgType: image, base64: base64);
          debugPrint(base64);
        });
      }
    }
  }

  onBankChanged({required BankModel model}) {
    state.country = model.key.toString();
    for (var element in state.banks) {
      if (element.value == model.value) {
        element.check = true;
      } else {
        element.check = false;
      }
    }
    update();
  }

  getBankCardInfo() async {
    final String token = await AccountUtil.getUserToken();
    final borrowId = Get.arguments["borrow_id"];
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;

    Request.postCallback(
      HttpUrls.getBankCardInfo,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          state.bank_notice = result.data["notice"];
          final List country = result.data["country"];
          state.banks =
              country.map((json) => BankModel.fromJson(json)).toList();



          update();
          if (state.banks.isNotEmpty) {
            //默认勾选第一项
            BankModel model = state.banks.first;
            onBankChanged(model: model) ;
          } 
        }
      },
    );
  }

  getAuthenticationInfo() async {
    final String token = await AccountUtil.getUserToken();
    final borrowId = Get.arguments["borrow_id"];
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;

    Request.postCallback(
      HttpUrls.getAuthenticationInfo,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);

        if (result.status == 0) {
          state.notice_verify = result.data["notice"];
          final Map record = result.data["record"];
          debugPrint("getAuthenticationInfo--$result");
          state.idcardAuthorization = record["idcard_authorization"];
          if (record["real_name"] != null) {
            name.text = record["real_name"];
          }
          if (record["id_number"] != null) {
            idNumber.text = record["id_number"];
          }
          if (record["gender"] != null) {
            gender.text = (record["gender"] == 1) ? "男" : "女";
          }

          //身份证正面照片
          if (record["id_number_positive_photo"] != null) {
            final Map id_number_positive_photo =
                record["id_number_positive_photo"];

            if (id_number_positive_photo["path"] != null) {
              state.positive_path = id_number_positive_photo["path"];
            }

            if (id_number_positive_photo["url"] != null) {
              state.positive = id_number_positive_photo["url"];
            }
          }

          if (record["id_number_reverse_photo"] != null) {
            //身份证反面照片
            final Map id_number_reverse_photo =
                record["id_number_reverse_photo"];
            if (id_number_reverse_photo["path"] != null) {
              state.reverse_path = id_number_reverse_photo["path"];
            }
            if (id_number_reverse_photo["url"] != null) {
              state.reverse = id_number_reverse_photo["url"];
            }
          }

          //是否开启ocr照片
          if (record["ocr"] != null) {
            final Map ocr = record["ocr"];
            if (ocr["open"] != null) {
              state.openOcr = ocr["open"];
            }
          }
          update();
        }
      },
    );
  }

  uploadImage({String? imgType, String? base64}) async {
    Loading.show("uplod_loding".tr);
    final String token = await AccountUtil.getUserToken();
    final borrowId = Get.arguments["borrow_id"];
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    map['img_type'] = imgType;
    map['base64'] = base64;

    Request.postCallback(
      HttpUrls.uploadUrl,
      data: map,
      success: (res) async {
        Loading.dismiss();
        ResultData result = ResultData.fromJson(res.data);

        if (result.status == 0) {
          String url = result.data["url"];
          String path = result.data["path"];
          debugPrint("result--$imgType---$url");
          switch (imgType) {
            case "id-card-front": //身份证正面
              state.positive = url;
              state.positive_path = path;
              update();
              break;
            case "id-card-reverse": //身份证反面
              state.reverse = url;
              state.reverse_path = path;
              update();
              break;
            case "ocr-image": //ocr人脸
              state.face = url;
              state.face_path = path;
              update();
              break;
            case "alipay-code": //支付宝图片
              state.alipay_code_url = url;
              state.alipay_code_path = path;
              update();
              break;  
            default:
          }
        }
      },
      error: (err) {
        Loading.dismiss();
      },
    );
  }

  uploadInfo() async {
    final String token = await AccountUtil.getUserToken();
    final borrowId = Get.arguments["borrow_id"];

    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;
    map['gender'] = (gender.text == "男") ? "1" : "2";
    map['real_name'] = name.text;
    map['id_number'] = idNumber.text;

    //身份证正面照片
    map['id_number_positive_photo'] = state.positive_path;
    //身份证反面照片
    map['id_number_reverse_photo'] = state.reverse_path;
    //手持身份证照片 map['id_number_handheld_photo'] = "";
    //hack分数「仅ocr开启时map
    //  map['hack_score'] = "100";
    // //ocr照片「仅ocr开启时」
    if (state.openOcr) {
      map['ocr_images'] = state.face_path;
    }
    Loading.show("上传中...");
    Request.postCallback(
      HttpUrls.uploadInfo,
      data: map,
      success: (res) async {
        Loading.dismiss();
        ResultData result = ResultData.fromJson(res.data);
        debugPrint("上传身份信息--$result");
        if (result.status == 0) {
          home_control.nextCertification(borrowId: borrowId);
        }
      },
      error: (err) {
        Loading.dismiss();
      },
    );
  }

  getInfoDetails() async {
    final String token = await AccountUtil.getUserToken();
    final borrowId = Get.arguments["borrow_id"];
    Map<String, dynamic> map = HashMap();
    map['token'] = token;
    map['borrow_id'] = borrowId;

    Request.postCallback(
      HttpUrls.getInfoDetail,
      data: map,
      success: (res) async {
        ResultData result = ResultData.fromJson(res.data);
        if (result.status == 0) {
          state.loan_purpose = result.data["enumeration"]["loan_purpose"];
          state.education = result.data["enumeration"]["education"];
          state.marital_status = result.data["enumeration"]["marital_status"];
          state.emergency_relation =
              result.data["enumeration"]["emergency_relation"];
          state.sesame_score = result.data["enumeration"]["sesame_score"];
          state.occupation = result.data["enumeration"]["occupation"];

          //填充基本信息返回
          final Map record = result.data["record"];

          state.notice_infor = result.data["notice"];

          //贷款用途
          final List loan_purpose_results = state.loan_purpose
              .where((model) => model["key"] == (record["loan_purpose"]))
              .toList();
          if (loan_purpose_results.isNotEmpty) {
            getFillPersonalInfo(
                info: "loan_purpose", map: loan_purpose_results.first);
          }

          //学历
          final List education_results = state.education
              .where((model) => model["key"] == (record["education"]))
              .toList();
          if (education_results.isNotEmpty) {
            getFillPersonalInfo(
                info: "education", map: education_results.first);
          }

          //婚姻状态
          final List marital_status_results = state.marital_status
              .where((model) => model["key"] == (record["marital_status"]))
              .toList();
          if (marital_status_results.isNotEmpty) {
            getFillPersonalInfo(
                info: "marital_status", map: marital_status_results.first);
          }

          //生日
          final date_of_birth = record["date_of_birth"];
          if (date_of_birth != null) {
            getFillPersonalInfo(
                info: "date_of_birth", map: {"value": date_of_birth});
          }

          //居住地址
          final List city_of_residences = record["city_of_residence"];
          if (city_of_residences.isNotEmpty) {
            if (city_of_residences.length > 3) {
              //居住地址详细地址
              user_city_of_residence_edit.text = city_of_residences.last;
              // 截取前三位
              List temList = city_of_residences;
              temList.removeLast();
              debugPrint("居住地址详细地址 截取前三位---$temList");
            }

            final city_of_residence = city_of_residences.join(",");
            getFillPersonalInfo(
                info: "city_of_residence", map: {"value": city_of_residence});
          }

          //职业
          final List occupation_results = state.occupation
              .where((model) => model["key"] == (record["occupation"]))
              .toList();
          if (occupation_results.isNotEmpty) {
            getFillPersonalInfo(
                info: "occupation", map: occupation_results.first);
          }

          //  芝麻分
          final List sesame_score_results = state.occupation
              .where((model) => model["key"] == (record["sesame_score"]))
              .toList();
          if (sesame_score_results.isNotEmpty) {
            getFillPersonalInfo(
                info: "sesame_score", map: sesame_score_results.first);
          }

          //  工作城市
          final List city_of_work_results = record["city_of_work"];
          if (city_of_work_results.isNotEmpty) {
            if (city_of_work_results.length > 3) {
              //工作城市详细地址
              user_city_of_work_edit.text = city_of_work_results.last;
              // 截取前三位
              List temList = city_of_work_results;
              temList.removeLast();
              debugPrint("截取前三位---$temList");
            }
            final city_of_work = city_of_work_results.join(",");
            getFillPersonalInfo(
                info: "city_of_work", map: {"value": city_of_work});
          }

          //常用联系人
          final List contacts = record["contacts"];
          if (contacts.isNotEmpty) {
            state.user_emergency_name_one = contacts.first["emergency_name"];
            state.user_emergency_name_two = contacts[1]["emergency_name"];

            //联系人关系关系一
            final emergency_relation = contacts.first["emergency_relation"];
            final List emergency_relation_one_results = state.emergency_relation
                .where((model) => model["key"] == (emergency_relation))
                .toList();
            if (emergency_relation_one_results.isNotEmpty) {
              getFillPersonalInfo(
                  info: "emergency_relation_one_results",
                  map: emergency_relation_one_results.first);
            }
            //联系人电话一
            final emergency_relation_one_results_phone =
                contacts.first["emergency_phone"];
            getFillPersonalInfo(
                info: "emergency_relation_one_results_phone",
                map: {"value": emergency_relation_one_results_phone});

            //联系人关系关系二
            final List emergency_relation_two_results = state.emergency_relation
                .where((model) =>
                    model["key"] == (contacts[1]["emergency_relation"]))
                .toList();
            if (emergency_relation_two_results.isNotEmpty) {
              getFillPersonalInfo(
                  info: "emergency_relation_two_results",
                  map: emergency_relation_two_results.first);
            }

            //联系人电话二
            final emergency_relation_two_results_phone =
                contacts[1]["emergency_phone"];
            getFillPersonalInfo(
                info: "emergency_relation_two_results_phone",
                map: {"value": emergency_relation_two_results_phone});

            debugPrint("联系人一 ---$emergency_relation_two_results_phone");
          }
        }
      },
    );
  }

  getFillPersonalInfo({required final String info, required Map map}) {
    switch (info) {
      case "loan_purpose":
        handleFillPersonalInfo(index: 0, map: map);
        break;

      case "education":
        handleFillPersonalInfo(index: 1, map: map);
        break;

      case "marital_status":
        handleFillPersonalInfo(index: 2, map: map);
        break;

      case "date_of_birth":
        handleFillPersonalInfo(index: 3, map: map);
        break;
      case "city_of_residence":
        handleFillPersonalInfo(index: 4, map: map);
        break;
      case "occupation":
        handleFillPersonalInfo(index: 7, map: map);
        break;
      case "sesame_score":
        handleFillPersonalInfo(index: 8, map: map);
        break;
      case "city_of_work":
        handleFillPersonalInfo(index: 9, map: map);
        break;
      case "emergency_relation_one_results":
        handleFillPersonalInfo(index: 12, map: map);
        break;

      case "emergency_relation_one_results_phone":
        handleFillPersonalInfo(index: 13, map: map);
        break;
      case "emergency_relation_two_results":
        handleFillPersonalInfo(index: 15, map: map);
        break;
      case "emergency_relation_two_results_phone":
        handleFillPersonalInfo(index: 16, map: map);
        break;
      default:
    }
  }

  //填写接口返回信息
  handleFillPersonalInfo({required int index, required Map map}) {
    ContactModel model = state.contact[index];

    switch (index) {
      case 0: //贷款用途
        model.value = map["value"];
        state.user_loan_purpose = map["key"].toString();
        update();
        break;

      case 1: //学历
        model.value = map["value"];
        state.user_education = map["key"].toString();
        update();
        break;

      case 2: //婚姻
        model.value = map["value"];
        state.user_marital_status = map["key"].toString();

        update();
        break;

      case 3: //生日
        model.value = map["value"];
        state.user_date_of_birth = map["value"];
        update();
        break;

      case 4: //居住地址
        model.value = map["value"];
        state.user_city_of_residence = map["value"];
        update();
        break;

      case 7: //职业
        model.value = map["value"];
        state.user_occupation = map["key"].toString();
        update();
        break;
      case 8: //芝麻分
        model.value = map["value"];
        state.user_sesame_score = map["key"].toString();
        update();
        break;

      case 9: //工作城市
        model.value = map["value"];
        state.user_city_of_work = map["value"];
        update();
        break;

      case 12: //联系人关系一

        model.value = map["value"];
        state.user_emergency_relation_one = map["key"].toString();
        update();
        break;
      case 13: //联系人电话一
        model.value = map["value"];
        state.user_emergency_phone_one = map["value"];
        update();
        break;
      case 15: //联系人关系二

        model.value = map["value"];
        state.user_emergency_relation_two = map["key"].toString();
        update();
        break;
      case 16: //联系人电话二

        model.value = map["value"];
        state.user_emergency_phone_two = map["value"];
        update();
        break;

      default:
    }
  }

  @override
  void onInit() {
    super.onInit();
    getAuthenticationInfo();
  }
}
